<template>
  <div>
    <el-row>
      <el-col :span="24">
        <span style="font-size:28px;fon">
          <b>请帅哥美女们把你的脸放摄像头面前:</b>
        </span>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" :offset="8">
        <video ref="video" width="500px" height="400px" autoplay></video>
      </el-col>
      <el-col :span="10" :offset="8">
        <canvas ref="canvas" width="500px" height="300px"></canvas>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" style="margin-left:750px; margin-top:50px">
        <el-button type="primary" @click="login">
          立即登录
          <i class="el-icon-upload el-icon--right"></i>
        </el-button>
      </el-col>
    </el-row>
  </div>
</template>  
    
  <script>
export default {
  name: "LoginPage",
  data() {
    return {
      stream: null
    };
  },
  mounted() {
    this.setupCamera();
  },
  methods: {
    setupCamera() {
      const constraints = {
        audio: false,
        video: {
          width: 1980,
          height: 1024
        }
      };

      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(stream => {
          this.$refs.video.srcObject = stream;
          this.$refs.video.onloadedmetadata = () => {
            this.$refs.video.play();
          };
        })
        .catch(error => console.error("Error accessing media devices.", error));
    },
    login() {
      const canvas = this.$refs.canvas;
      const context = canvas.getContext("2d");
      context.drawImage(this.$refs.video, 0, 0, 530, 300);
      const base64 = this.getBase64(canvas);

      // 假设你正在使用axios进行HTTP请求
      // 如果未安装axios，请运行 npm install axios --save
      this.$axios
        .post("api/uums-server/faceLog", { base: base64 })
        .then(response => {
          console.log(response.data);
          if (response.data.code == 200) {
            this.$message.success("登录成功!");
            localStorage.setItem("token", response.data.data);
            this.$router.push({ path: "/" });
            this.stopCamera();
          } else {
            alert("人脸匹配失败,请重新刷脸登录");
          }
        })
        .catch(error => console.error("Error logging in with face.", error));
    },
    getBase64(canvas) {
      return canvas.toDataURL("image/png").split("base64,")[1];
    },
    stopCamera() {
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
        this.$refs.video.srcObject = null;
      }
    }
  }
};
</script>  
    
  <style scoped>
</style>